/* GNU Guix --- Functional package management for GNU
   Copyright (C) 2021 Ludovic Courtès <ludo@gnu.org>

   This file is part of GNU Guix.

   GNU Guix is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or (at
   your option) any later version.

   GNU Guix is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.  */

// Inspired by these examples:
// https://observablehq.com/@d3/force-directed-graph
// https://observablehq.com/@d3/mobile-patent-suits

// Visibility of the "undo" button.
var undoVisibility = "hidden";

// ID of a highlighted node.
var highlightedNodeID = null;

chart = function(links, nodes) {
    console.log("chart with " + nodes.length + " nodes and "
		+ links.length + " edges");

    // Return the radius used for the "collision" force.
    function collisionRadius(node) {
	if (node.label == "system") return 10;
	else if (node.category == "essential") return 5;
	else if (node.category == "base") return 3;
	else return 1;
    }

    const simulation = d3.forceSimulation(nodes)
	  .force("link", d3.forceLink(links).id(d => d.id))
	  .force("charge", d3.forceManyBody()) //.strength(-100)

          // Center the mean position of all nodes.
	  .force("center", d3.forceCenter(width / 2, height / 2))

          // Force "important" nodes further apart.
	  .force("collision", d3.forceCollide(collisionRadius));

    const textArea = d3.select("div#container")
	  .append("div").classed("text-area", true)
	  .attr("x", 4).attr("y", 4);

    const controlArea = d3.select("div#container")
	  .append("div").classed("control-area", true);

    function redraw() {
	d3.selectAll(".svg-content").remove();
	d3.selectAll(".text-area").remove();
	d3.selectAll(".control-area").remove();

	drawGraph();
    }

    const svg = d3.select("div#container")
	  .append("svg")
	  .attr("preserveAspectRatio", "xMinYMin meet")
	  .attr("viewBox", [0, 0, width, height])
	  .classed("svg-content", true)
	  .on("click", x => {
	      // Clicking in the blank area of the SVG deletes the
	      // currently displayed value.
	      d3.selectAll(".service-value").remove();
	  });

    // build the arrow.
    svg.append("svg:defs").selectAll("marker")
	.data(["arrow"])      // Different link/path types can be defined here
	.enter().append("marker")    // This section adds in the arrows
	.attr("id", String)
	.attr("viewBox", "0 -5 10 10")
	.attr("refX", 15)
	.attr("refY", -1.5)
	.attr("markerWidth", 6)
	.attr("markerHeight", 6)
	.attr("orient", "auto")
	.attr("fill", "#999")
	.append("svg:path")
	.attr("d", "M0,-5L10,0L0,5");

    const link = svg.append("g")
	  .attr("stroke", "#999")
	  .attr("stroke-opacity", 0.6)
	  .selectAll("line")
	  .data(links)
	  .join("line")
	  .classed("edge", true)
	  .attr("marker-end", "url(#arrow)")
    	  .on("click", event => {
	      // Display the service value.
	      const edge = event.target.__data__;
	      d3.selectAll(".service-value").remove();
	      d3.text("/edge/" + edge.source.id + "/" + edge.target.id)
		  .then(element => {
		      textArea.append("div").classed("service-value", true)
			  .html(element);
		  });
	  });

    function nodeColor (node) {
	if (node.category == "essential") return "#ff4466";
	else if (node.category == "base") return "#bb3344";
	else if (node.category == "desktop") return "#3344bb";
	else return "#bbb";
    }

    function nodeRadius(node) {
	if (node.label == "system") return 6;
	else if (node.category == "essential") return 3;
	else return 1;
    }

    function labelColor(node) {
	if (node.category == "essential") return "#000";
	else return "#422";
    }

    const node = svg.append("g")
	  .attr("fill", "currentColor")
	  .attr("stroke-linecap", "round")
	  .attr("stroke-linejoin", "round")
	  .selectAll("g")
	  .data(nodes)
	  .join("g")
	  .call(drag(simulation));

    node.append("circle")
	.attr("stroke", "none")
    	.attr("r", nodeRadius)
	.attr("fill", nodeColor)
	.append("title")
	.text(d => d.label);

    node.append("text")
	.attr("x", 0)
	.attr("y", 0)
	.attr("font-size", "4px")
	.attr("color", labelColor)
	.attr("text-align", "center")
	.classed("highlighted-node", n => {
	    return n.id == highlightedNodeID;
	})
	.text(d => d.label)
	.on("mouseover", event => {
	    // Display service type documentation.
	    d3.select(event.target).attr("font-weight", "bold");
	    // XXX: Is there a better way than accessing __data__?
	    const node = event.target.__data__;
	    const description = textArea
		  .append("div").classed("node-description", true)
	    description.append("div").classed("node-category", true)
		.text("category: " + node.category);
	    description.append("div").html(node.description);
	})
	.on("click", event => {
	    // Display the service value.
	    const node = event.target.__data__;
	    d3.selectAll(".service-value").remove();
	    d3.text("/value/" + node.id)
		.then(element => {
		    textArea.append("div").classed("service-value", true)
			.html(element);
		});
	})
	.on("mouseout", event => {
	    d3.select(event.target).attr("font-weight", "normal");
	    d3.selectAll(".node-description").remove();
	})
	.on("dblclick", event => {
	    const node = event.target.__data__;
	    console.log("folding " + node.id);
	    d3.json("/fold/" + node.id).then(folded => {
		undoVisibility = "visible";
		highlightedNodeID = folded.id;
		redraw();
	    });
	})
	.clone(true).lower()
	.attr("fill", "none")
	.attr("stroke", "white")
	.attr("stroke-width", 3);


    simulation.on("tick", () => {
	link
            .attr("x1", d => d.source.x)
            .attr("y1", d => d.source.y)
            .attr("x2", d => d.target.x)
            .attr("y2", d => d.target.y);

	node
	    .attr("transform", d => `translate(${d.x},${d.y})`);
    });

    // invalidation.then(() => simulation.stop());

    controlArea.append("div").classed("button", true)
	.attr("id", "undo-button")
	.style("visibility", undoVisibility)
	.text("⎌")
	.on("click", event => {
	    console.log("undo!");
	    d3.text("/undo").then(redraw);
	});

    controlArea.append("div").classed("button", true)
	.text("⌧")
	.on("click", event => {
	    console.log("reset!");
	    d3.text("/reset").then(() => {
		undoVisibility = "hidden";
		redraw();
	    });
	});

    return svg.node();
}

// height = document.documentElement.clientWidth;
// width = document.documentElement.clientHeight;
height = 200;
width = 300;

color = function() {
    const scale = d3.scaleOrdinal(d3.schemeCategory10);
    return d => scale(d.group);
}

drag = function (simulation) {
    
    function dragstarted(event) {
	if (!event.active) simulation.alphaTarget(0.3).restart();
	event.subject.fx = event.subject.x;
	event.subject.fy = event.subject.y;
    }
    
    function dragged(event) {
	event.subject.fx = event.x;
	event.subject.fy = event.y;
    }
    
    function dragended(event) {
	if (!event.active) simulation.alphaTarget(0);
	event.subject.fx = null;
	event.subject.fy = null;
    }
    
    return d3.drag()
	.on("start", dragstarted)
	.on("drag", dragged)
	.on("end", dragended);
}

drawGraph = function() {
    // Get the nodes and edges from the server as JSON.
    d3.json("/edges")
	.then(function(edges) {
	    console.log("edges!");
	    console.log(edges);
	    d3.json("/nodes")
		.then(function (nodes) {
		    console.log("nodes!");
		    console.log(nodes);

		    // Create the SVG.
		    chart(edges, nodes);
		});
	});
}

console.log("starting!");
drawGraph();
